﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.Product;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class ProductBrandsController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(ProductBrandsModel model)
        {
            var total = 0;
            var list = ServiceFactory.ProductBrandsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.BrandName,
                o.CreateBy,
                CreateTime = o.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.ImgUrl,
                o.IsAvailable,
                LastModifyTime = o.LastModifyTime.ToString("yyyy-MM-dd HH:mm:ss"),
                o.LastModifyBy,
                o.Sort,
                o.Remark,
                o.BrandCode,
                o.ProductType.ProductName
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(int id)
        {
            var productBrand = ServiceFactory.ProductBrandsServiceInstance.LoadByID(id);
            return View(productBrand);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveProductBrand(ProductBrands model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            var serv = ServiceFactory.ProductBrandsServiceInstance;
            var imageUrlFile = Request.Files["ImgUrl"];
            var imageUrlPath = FileHelper.UploadFile(imageUrlFile, Server);
            if (model.ID == 0)
            {
                if (serv.IsExist(model.BrandName))
                {
                    responseResult.Message = "该品牌已经存在";
                    TempData["ResponseResult"] = responseResult;
                    return RedirectToAction("Edit", new { id = model.ID });
                }
                model.CreateTime = DateTime.Now;
                model.CreateBy = CurrentUser.UserAccount;
                model.LastModifyBy = CurrentUser.UserAccount;
                model.LastModifyTime = DateTime.Now;
                model.ImgUrl = string.IsNullOrWhiteSpace(imageUrlPath) ? model.ImgUrl : imageUrlPath;
                using (TransactionScope ts = new TransactionScope())
                {
                    var entity = serv.AddEntities(model);
                    responseResult.Success = entity.ID > 0;
                    if (!responseResult.Success)
                    {
                        ts.Dispose();
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("Edit", new { id = model.ID });
                    }
                    //设置编码
                    entity.BrandCode = CommonMethod.GenerateCode("PP", entity.ID.ToString(), 6);
                    if (!serv.UpdateEntities(entity))
                    {
                        ts.Dispose();
                        responseResult.Message = "操作失败！设置品牌编码失败";
                        TempData["ResponseResult"] = responseResult;
                        return RedirectToAction("Edit", new { id = model.ID });
                    }
                    ts.Complete();
                }
            }
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        try
                        {
                            if (entity.BrandName != model.BrandName && serv.IsExist(model.BrandName, model.ID))
                            {
                                responseResult.Message = "已存在同名的品牌，请修改品牌名.";
                            }
                            else
                            {
                                //entity = ReflectHelper<ProductBrands, ProductBrands>.CloneT1ToT2(model, entity);
                                if (!string.IsNullOrWhiteSpace(imageUrlPath))
                                {
                                    entity.ImgUrl = imageUrlPath;
                                }
                                entity.BrandName = model.BrandName;
                                entity.ProductTypeId = model.ProductTypeId;
                                entity.Sort = model.Sort;
                                entity.IsAvailable = model.IsAvailable;
                                entity.Remark = model.Remark;
                                entity.LastModifyBy = CurrentUser.UserAccount;
                                entity.LastModifyTime = DateTime.Now;
                                var flag = ServiceFactory.ProductBrandsServiceInstance.UpdateEntities(entity);
                                responseResult.Success = flag;
                                ts.Complete();
                            }
                        }
                        catch (Exception)
                        {
                            ts.Dispose();
                        }
                    }
                }
                else
                {
                    responseResult.Message = "该品牌不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("Index") : RedirectToAction("Edit", new { id = model.ID });
        }

        /// <summary>
        /// 启用或禁用品牌
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isAvailable"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.ProductBrandsServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.ProductBrandsServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }


        #region 获取品牌 + JsonResult GetProductBrands(int productTypeId)
        public JsonResult GetProductBrands(int productTypeId)
        {
            var entities = ServiceFactory.ProductBrandsServiceInstance.LoadEntities(o => o.ProductTypeId == productTypeId && o.IsAvailable == true).Select(t => new
            {
                t.ID,
                t.BrandName
            }).AsNoTracking().ToList();
            return Json(new { Result = true, Data = entities }, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
